package com.chen.springboostart.controller;

import com.chen.springboostart.dto.User;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
public class HelloController {
    @RequestMapping("/hello")
    public String hello() {
        System.out.println("Hello World");
        return "Hello World";
    }

    // 接收json类型的数据,必须@RequestBody
    @GetMapping("/test5")
    public String test5(@RequestBody List<User> users) {
        for (User user : users) {
            System.out.println(user);
        }
        return "OK";
    }

    // springBoot接收参数的方式
    // 必须保证参数名字一致，如果参数不一致，使用RequestParam,但是这是默认必须，如果没有传入参数，或报错
    @GetMapping("/test4")
    public String test4(@RequestParam("name") String username, @RequestParam("pwd") String password, int age) {
        System.out.println(username);
        System.out.println(password);
        System.out.println(age);
        return "Hello " + username + " " + password + ", age " + age;
    }

    // springBoot接收参数的方式
    // 必须保证参数名字一致，启用POST方法，参数在请求体中，不可使用json数据
    @PostMapping("/test3")
    public String test3(String name, String pwd, int age) {
        System.out.println(name);
        System.out.println(pwd);
        System.out.println(age);
        return "Hello " + name + " " + pwd + ", age " + age;
    }

    // springBoot接收参数的方式
    // 必须保证参数名字一致
    @GetMapping("/test2")
    public String test2(String name, String pwd, int age) {
        System.out.println(name);
        System.out.println(pwd);
        System.out.println(age);
        return "Hello " + name + " " + pwd + ", age " + age;
    }

    // 获取参数的原始方法
    @GetMapping("/test1")
    public String test1(HttpServletRequest request) {
        String name = request.getParameter("name");
        String pwd = request.getParameter("pwd");
        String age = request.getParameter("age");
        // 如果想获取一个int类型数据，需要手动转换
        int myage = Integer.parseInt(age);
        System.out.println(name);
        System.out.println(pwd);
        System.out.println(age);
        return "Hello " + name + " " + pwd + ", age " + myage;
    }
}
